import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Space, Modal, message, Checkbox } from 'antd';
import styles from './RoleManagement.module.css';
import { _apiRoleList } from '../../../api';

const RoleManagement = () => {
  // 添加权限列表常量
  const permissionsList = [
    '账号管理', '分店管理', '会员管理',
    '优惠券管理', '积分管理', '基础设置',
    '图片管理', '数据统计'
  ];

  const [roles, setRoles] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [formData, setFormData] = useState({
    roleName: '',
    description: '',
    permissions: []
  });
  
  // 添加编辑状态
  const [editingRole, setEditingRole] = useState(null);

  // 添加 loading 状态
  const [loading, setLoading] = useState(false);

  // 修改模态框标题显示
  const modalTitle = editingRole ? '编辑角色' : '新增角色';

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      key: 'index',
      width: 80,
      render: (_, __, index) => index + 1,
    },
    {
      title: '角色名称',
      dataIndex: 'title',
      key: 'title',
    },
    // {
    //   title: '菜单权限',
    //   dataIndex: 'permissions',
    //   key: 'permissions',
    // },
    // {
    //   title: '创建时间',
    //   dataIndex: 'createTime',
    //   key: 'createTime',
    // },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          {/* <Button type="link" onClick={() => handleEdit(record)}>编辑</Button> */}
          <Button type="link" danger onClick={() => handleDelete(record)}>删除</Button>
        </Space>
      ),
    },
  ];

  // 获取角色列表数据
  const fetchRoleList = async () => {
    try {
      setLoading(true);
      const response = await _apiRoleList();
      console.log('角色列表数据:', response);
      
      if (response?.data) {
        setRoles(response.data);
      }
    } catch (error) {
      console.error('获取角色列表失败:', error);
      message.error('获取角色列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 在组件加载时获取数据
  useEffect(() => {
    fetchRoleList();
  }, []);

  // 处理搜索
  const handleSearch = (value) => {
    setSearchText(value);
    // 实现搜索逻辑
  };

  // 处理新增
  const handleAdd = () => {
    setIsModalVisible(true);
  };

  // 处理编辑
  const handleEdit = (record) => {
    setEditingRole(record);
    setFormData({
      roleName: record.roleName || '',
      description: record.description || '',
      // 添加空值判断，如果 permissions 为空则设为空数组
      permissions: record.permissions ? record.permissions.split('，').filter(Boolean) : []
    });
    setIsModalVisible(true);
  };

  // 修改模态框确认处理
  const handleModalOk = () => {
    if (!formData.roleName) {
      message.error('请输入角色名称');
      return;
    }

    if (editingRole) {
      // 处理编辑保存
      const updatedRoles = roles.map(role => {
        if (role.id === editingRole.id) {
          return {
            ...role,
            roleName: formData.roleName,
            permissions: formData.permissions.join('，'),
            description: formData.description
          };
        }
        return role;
      });
      setRoles(updatedRoles);
      message.success('编辑成功');
    } else {
      // 处理新增保存
      const newRole = {
        id: roles.length + 1,
        roleName: formData.roleName,
        permissions: formData.permissions.join('，'),
        description: formData.description,
        createTime: new Date().toLocaleString()
      };
      setRoles([...roles, newRole]);
      message.success('新增成功');
    }
    handleModalCancel();
  };

  // 修改模态框取消处理
  const handleModalCancel = () => {
    setIsModalVisible(false);
    setFormData({ roleName: '', description: '', permissions: [] });
    setEditingRole(null);
  };

  // 处理表单数据变化
  const handleFormChange = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理删除
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除角色"${record.roleName}"吗？`,
      onOk: () => {
        // 实现删除逻辑
        message.success('删除成功');
      },
    });
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.title}>当前位置：角色管理</div>
        <div className={styles.operations}>
          <Space>
            <Button type="primary" onClick={handleAdd}>新增</Button>
            {/* <Button onClick={() => handleDelete(null)}>删除</Button> */}
            <Input.Search
              placeholder="请输入角色名称"
              allowClear
              onSearch={handleSearch}
              style={{ width: 200 }}
            />
          </Space>
        </div>
      </div>
      
      <Table
        loading={loading}
        columns={columns}
        dataSource={roles}
        rowKey="id"
        pagination={{
          total: roles.length,
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      <Modal
        title={modalTitle}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
      >
        <div style={{ marginBottom: 16 }}>
          <div style={{ marginBottom: 8 }}>角色名称：</div>
          <Input
            value={formData.roleName}
            onChange={e => handleFormChange('roleName', e.target.value)}
            placeholder="请输入角色名称"
          />
        </div>
        <div style={{ marginBottom: 16 }}>
          <div style={{ marginBottom: 8 }}>角色简介：</div>
          <Input.TextArea
            value={formData.description}
            onChange={e => handleFormChange('description', e.target.value)}
            placeholder="请输入角色简介"
          />
        </div>
        <div>
          <div style={{ marginBottom: 8 }}>角色权限：</div>
          <div>
            <Checkbox
              checked={formData.permissions.length === permissionsList.length}
              onChange={(e) => {
                const newPerms = e.target.checked ? permissionsList : [];
                handleFormChange('permissions', newPerms);
              }}
            >
              全选
            </Checkbox>
          </div>
          <div style={{ marginTop: 8 }}>
            {[
              ['账号管理', '分店管理', '会员管理'],
              ['优惠券管理', '积分管理', '基础设置'],
              ['图片管理', '数据统计']
            ].map((row, index) => (
              <div key={index} style={{ marginBottom: 8 }}>
                {row.map(perm => (
                  <Checkbox
                    key={perm}
                    checked={formData.permissions.includes(perm)}
                    onChange={(e) => {
                      const newPerms = e.target.checked
                        ? [...formData.permissions, perm]
                        : formData.permissions.filter(p => p !== perm);
                      handleFormChange('permissions', newPerms);
                    }}
                    style={{ marginRight: 16 }}
                  >
                    {perm}
                  </Checkbox>
                ))}
              </div>
            ))}
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default RoleManagement;
